<template>
  <div>
    <el-dialog
      title="推荐课程列表"
      :visible="open"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="1400px"
      append-to-body
      @close="cancel()"
    >
      <div v-loading="recommendLoading">
        <div class="search_collect">
          <el-form
            :model="model"
            ref="queryForm"
            size="small"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="">
              <el-input
                v-model="model.courseName"
                placeholder="请输入课程名称"
                clearable
              />
            </el-form-item>
            <el-form-item
              v-if="this.$store.getters.roleId != 'branchAdmin'"
              label=""
            >
              <el-select
                filterable
                v-model="model.branchId"
                placeholder="请选择分院名称"
                clearable
              >
                <el-option
                  v-for="item in branchList"
                  :key="item.branchId"
                  :label="item.branchName"
                  :value="item.branchId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-select
                filterable
                v-model="model.principalId"
                placeholder="请选择主讲教师"
                clearable
              >
                <el-option
                  v-for="item in teacherList"
                  :key="item.teacherId"
                  :label="item.name"
                  :value="item.teacherId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-select
                filterable
                v-model="model.courseType"
                placeholder="请选择课程类型"
                clearable
              >
                <el-option
                  v-for="(item, index) of dict.type.course_type"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-select
                filterable
                v-model="model.courseTemplate"
                placeholder="请选择课程模版"
                clearable
              >
                <el-option label="全部" :value="''"></el-option>
                <el-option label="通用模版" :value="0"></el-option>
                <el-option label="工学一体模版" :value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-select
                filterable
                v-model="model.sortSearch"
                placeholder="请选择排序"
              >
                <el-option
                  v-for="item in sortList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                v-preventReClick
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleSearch"
              >搜索
              </el-button
              >
              <el-button
                v-preventReClick
                icon="el-icon-refresh"
                size="mini"
                @click="resetSearch"
              >重置
              </el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="overflow_auto">
          <vuedraggable
            ghost-class="custom_ghost"
            :sort="root"
            @change="handleChange"
            v-model="recommendCourseList"
            group="site"
            class="course_collect"
            animation="300"
          >
            <div
              @click="routeTo(item)"
              class="course_card"
              v-for="(item, index) in recommendCourseList"
              :key="index"
            >
              <div
                v-if="item.type == 0 || item.type == 1"
                class="tag"
                :class="{ bg_green: item.type == 1, bg_orange: item.type == 0 }"
              >
                {{ item.type == 0 ? '学校推荐' : '分院推荐' }}
              </div>
              <div
                class="buttons"
                v-if="
                  root &&
                  ($store.getters.curRole == 'schoolAdmin' ||
                    ($store.getters.branchId == item.branchId &&
                      item.type != 0))
                "
              >
                <div
                  v-if="$store.getters.curRole == 'schoolAdmin'"
                  @click.stop="handleSure('1', item)"
                  class="btn_item"
                >
                  置顶
                </div>
                <div
                  v-if="$store.getters.curRole == 'schoolAdmin'"
                  @click.stop="handleSure('2', item)"
                  class="btn_item"
                >
                  置底
                </div>
                <div @click.stop="handleSure('3', item)" class="btn_item">
                  移除
                </div>
              </div>
              <img class="img" :src="item.coursePic" alt="加载失败"/>
              <div class="course_name">
                <span v-if="item.courseType == 3">(工学一体)</span>
                <tooltip
                  position="top"
                  :text="item.courseName"
                  :width="item.courseType == 3 ? 'calc(100% - 80px)' : '100%'"
                />
              </div>
              <div class="branch_name">
                <tooltip position="top" :text="item.branchName" width="100%"/>
              </div>
              <div class="card_bottom">
                <div class="teacher_name">{{ item.principalName }}</div>
                <el-popover placement="bottom" trigger="hover">
                  <div class="hover_content">
                    <div class="hover_left">
                      <div class="left_label">基础数据</div>
                      <div class="item">
                        <div class="label">题目数：</div>
                        <div class="value">
                          {{
                            item.topicNum
                              ? item.topicNum.toLocaleString('en-US')
                              : 0
                          }}
                        </div>
                      </div>
                      <div class="item">
                        <div class="label">考核数：</div>
                        <div class="value">
                          {{
                            item.examPaperNum
                              ? item.examPaperNum.toLocaleString('en-US')
                              : 0
                          }}
                        </div>
                      </div>
                      <div class="item">
                        <div class="label">练习数：</div>
                        <div class="value">
                          {{
                            item.practicePaperNum
                              ? item.practicePaperNum.toLocaleString('en-US')
                              : 0
                          }}
                        </div>
                      </div>
                    </div>
                    <div class="hover_left ml20">
                      <div class="left_label">学习数据</div>
                      <div class="item">
                        <div class="label">点击量：</div>
                        <div class="value">
                          {{
                            item.clickNum
                              ? item.clickNum.toLocaleString('en-US')
                              : 0
                          }}
                        </div>
                      </div>
                      <div class="item">
                        <div class="label">在学人数：</div>
                        <div class="value">
                          {{
                            item.stuStudyNum
                              ? item.stuStudyNum.toLocaleString('en-US')
                              : 0
                          }}
                        </div>
                      </div>
                      <div class="item">
                        <div class="label">结课人数：</div>
                        <div class="value">
                          {{
                            item.finishNum
                              ? item.finishNum.toLocaleString('en-US')
                              : 0
                          }}
                        </div>
                      </div>
                    </div>
                    <div class="hover_left ml20">
                      <div class="left_label">考核数据</div>
                      <div class="item">
                        <div class="label">累计考核人次：</div>
                        <div class="value">
                          {{
                            item.examNum
                              ? item.examNum.toLocaleString('en-US')
                              : 0
                          }}
                        </div>
                      </div>
                      <div class="item">
                        <div class="label">生均考核次数：</div>
                        <div class="value">
                          {{
                            item.avgExamNum
                              ? item.avgExamNum.toLocaleString('en-US')
                              : 0
                          }}
                        </div>
                      </div>
                      <div class="item">
                        <div class="label">首考通过率：</div>
                        <div class="value">
                          {{
                            item.firstExamPassingRate
                              ? item.firstExamPassingRate
                              : 0
                          }}%
                        </div>
                      </div>
                      <div class="item">
                        <div class="label">重考人次：</div>
                        <div class="value">
                          {{
                            item.applyNum
                              ? item.applyNum.toLocaleString('en-US')
                              : 0
                          }}
                        </div>
                      </div>
                      <div class="item">
                        <div class="label">生均重考次数：</div>
                        <div class="value">
                          {{
                            item.avgApplyNum
                              ? item.avgApplyNum.toLocaleString('en-US')
                              : 0
                          }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div slot="reference" class="learn_num">
                    <img
                      class="icon_task"
                      src="@/assets/images/icon_task.png"
                      alt="加载失败"
                    />
                    <div class="value">{{ item.examNum }}</div>
                  </div>
                </el-popover>
              </div>
            </div>
          </vuedraggable>
          <div v-if="recommendCourseList.length == 0" class="empty_box">
            <el-empty description="暂无推荐课程"></el-empty>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCourseRecommend,
  editCourseRecommend,
  deleteCourseRecommend,
  sortCourseRecommend
} from '@/api/home'
import { listPost_teacher } from '@/api/schoolOrganization/teacher'
import { listPost_branch } from '@/api/schoolOrganization/organization'
import vuedraggable from 'vuedraggable'

export default {
  name: 'detialDialog',
  components: { vuedraggable },
  dicts: ['course_type'],
  props: {
    open: {
      type: Boolean,
      default: false
    },
    root: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    open(e) {
      if (e) {
        if (this.$store.getters.roleId == 'branchAdmin' && this.root) {
          this.model.branchId = this.$store.getters.branchId
        }
        this.getTeacher()
        this.getBranch()
        this.getCourseRecommend()
      }
    },
    'model.branchId': {
      handler(val) {
        this.getTeacher()
      },
      deep: true
    }
  },
  data() {
    return {
      showRoot: false,
      //推荐课程列表
      recommendCourseList: [],
      //主讲教师列表
      teacherList: [],
      //分院列表
      branchList: [],
      model: {
        courseTemplate: '',
        sortSearch: 9,
        courseType: '',
        principalId: '',
        branchId: '',
        courseName: '',
        pageNum: 1,
        pageSize: 9999
      },
      recommendLoading: false,
      sortList: [
        {
          value: 9,
          label: '综合排序'
        },
        {
          value: 0,
          label: '最新发布时间'
        },
        {
          value: 1,
          label: '累计考核次数(由高到低)'
        },
        {
          value: 2,
          label: '累计考核次数(由低到高)'
        },
        {
          value: 3,
          label: '累计结课人数(由高到低)'
        },
        {
          value: 4,
          label: '累计结课人数(由低到高)'
        },
        {
          value: 5,
          label: '当前在学人数(由高到低)'
        },
        {
          value: 6,
          label: '当前在学人数(由低到高)'
        },
        {
          value: 7,
          label: '课程总点击量(由高到低)'
        },
        {
          value: 8,
          label: '课程总点击量(由低到高)'
        }
      ]
    }
  },
  methods: {
    routeTo(item) {
      this.$router.push({
        path: '/course/addCourse',
        query: {
          from: 'recommend',
          courseId: item.courseId,
          branchId: item.branchId,
          type: 'detail'
        }
      })
      this.cancel()
    },
    //获取推荐课程列表
    async getCourseRecommend() {
      this.recommendLoading = true
      try {
        let res = await getCourseRecommend(this.model)
        const { code, rows } = res
        if (code === 200) {
          this.recommendLoading = false
          this.recommendCourseList = rows
        }
      } catch (e) {
        console.error(e)
      } finally {
      }
    },
    //置顶&&置底
    async editCourseRecommend(item, type) {
      const loading = this.$loading({
        lock: true,
        text: '正在处理...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      try {
        let params = {
          id: item.id,
          top: type
        }
        let res = await editCourseRecommend(params)
        const { code } = res
        if (code === 200) {
          this.$modal.msgSuccess(`${type == 1 ? '置顶' : '置底'}成功`)
          this.getCourseRecommend()
          this.$emit('refreshData', true)
        }
      } catch (e) {
        console.error(e)
      } finally {
        loading.close()
      }
    },
    handleChange(e) {
      this.sortCourseRecommend()
    },
    async sortCourseRecommend() {
      let arr = []
      for (const recommendCourseListElement of this.recommendCourseList) {
        arr.push(recommendCourseListElement.id)
      }
      try {
        let res = await sortCourseRecommend(arr)
        const { code } = res
        if (code === 200) {
          this.$modal.msgSuccess(`排序成功`)
          this.$emit('refreshData', true)
        }
      } catch (e) {
        console.error(e)
      }
    },
    handleSure(type, item) {
      let text = {
        1: `确认将《${item.courseName}》置顶吗？`,
        2: `确认将《${item.courseName}》置底吗？`,
        3: `确认将《${item.courseName}》从推荐课程列表中移除吗？`
      }
      let titleText = {
        1: `置顶`,
        2: `置底`,
        3: `移除`
      }
      this.$confirm(text[type], `${titleText[type]}提示`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (type == 1) {
            this.editCourseRecommend(item, 1)
          }
          if (type == 2) {
            this.editCourseRecommend(item, -1)
          }
          if (type == 3) {
            this.deleteCourseRecommend(item)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // 移除推荐课程
    async deleteCourseRecommend(item) {
      const loading = this.$loading({
        lock: true,
        text: '正在处理...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      try {
        let res = await deleteCourseRecommend(item.id)
        const { code } = res
        if (code === 200) {
          this.$modal.msgSuccess(`移除成功`)
          this.getCourseRecommend()
          this.$emit('refreshData', true)
        }
      } catch (e) {
        console.error(e)
      } finally {
        loading.close()
      }
    },
    handleSearch() {
      this.getCourseRecommend()
    },
    resetSearch() {
      this.model = {
        sortSearch: 9,
        courseType: '',
        principalId: '',
        branchId: '',
        courseName: '',
        pageNum: 1,
        pageSize: 9999,
        courseTemplate: ''
      }
      if (this.$store.getters.roleId == 'branchAdmin' && this.root) {
        this.model.branchId = this.$store.getters.branchId
      }
      this.getCourseRecommend()
    },
    cancel() {
      this.$emit('update:open', false)
    },
    // 获取教师列表
    getTeacher() {
      listPost_teacher({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId,
        branchId: this.model.branchId
      }).then((response) => {
        this.teacherList = response.rows
      })
    },
    getBranch() {
      listPost_branch({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId
      }).then((response) => {
        this.branchList = response.rows
      })
    }
  }
}
</script>

<style scoped lang="scss">
.search_collect {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.overflow_auto {
  height: calc(100vh - 270px);
  overflow: auto;
}

.course_collect {
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(228px, 1fr));
  grid-gap: 20px;
  justify-content: center;

  .course_card {
    flex: 0 0 auto; /* 不拉伸，固定宽度 */
    width: 228px;
    height: 242px;
    background: #ffffff;
    border-radius: 18px;
    border: 1px solid #ebebeb;
    cursor: pointer;
    margin: 0 20px 24px 0;
    position: relative;

    &:hover {
      .buttons {
        display: block;
      }
    }

    .tag {
      position: absolute;
      top: 0;
      left: 0;
      width: 72px;
      height: 21px;
      border-radius: 9px 0 9px 0;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 600;
      font-size: 14px;
      color: #ffffff;
      text-align: center;
    }

    .buttons {
      display: none;
      position: absolute;
      right: 14px;
      top: 8px;

      .btn_item {
        width: 40px;
        height: 16px;
        background: rgba(255, 255, 255, 0.8);
        border-radius: 9px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 400;
        font-size: 12px;
        color: #050505;
        user-select: none;
        cursor: pointer;
        margin-bottom: 8px;

        &:active {
          background: darken(rgba(255, 255, 255, 0.8), 10%);
          color: darken(#050505, 18%);
        }
      }
    }

    .img {
      width: 100%;
      height: 156px;
      background: #24044e;
      border-radius: 9px 9px 0 0;
    }

    .course_name {
      margin-top: 4px;
      padding: 0 0 0 12px;
      box-sizing: border-box;
      line-height: 22px;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 600;
      font-size: 17px;
      color: #333333;

      span {
        font-weight: 500;
        font-size: 12px;
        color: #f89a33;
        margin-right: 6px;
      }
    }

    .branch_name {
      padding: 0 12px 0 12px;
      box-sizing: border-box;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 400;
      font-size: 14px;
      line-height: 20px;
      color: #999999;
    }

    .card_bottom {
      line-height: 22px;
      padding: 0 12px 0 12px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .teacher_name {
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 400;
        font-size: 13px;
        color: #999999;
      }

      .learn_num {
        display: flex;
        align-items: center;

        .icon_task {
          width: 16px;
        }

        .value {
          margin-left: 4px;
          font-family: PingFangSC, PingFang SC, sans-serif;
          font-weight: 400;
          font-size: 13px;
          color: #999999;
        }
      }
    }
  }
}

.bg_orange {
  background: #f89a33;
}

.bg_green {
  background: #11a983;
}

::v-deep .el-popover .el-popper {
  background: #ffffff;
  box-shadow: 0 0 20px 0 rgba(0, 74, 88, 0.1);
  border-radius: 8px !important;
  padding: 12px 16px;
  box-sizing: border-box;
}

.hover_content {
  display: flex;
  padding: 16px;
  box-sizing: border-box;

  .hover_left {
    .left_label {
      font-size: 18px;
      color: #1ab394;
      font-weight: bold;
    }

    .item {
      display: flex;
      align-items: center;
      padding: 6px 12px;
      box-sizing: border-box;

      .label {
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 400;
        font-size: 14px;
        color: #999999;
      }

      .value {
        font-family: PingFangSC, PingFang SC, sans-serif;
        font-weight: 400;
        font-size: 14px;
        color: #333333;
      }
    }

    .item:first-child {
      margin-top: 0;
    }
  }
}

.custom_ghost {
  background-color: transparent; /* 设置被拖拽元素的背景色为红色 */
}
</style>
